<template>
  <div class="work-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">艺人作品管理</h1>
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        新增作品
      </el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索作品标题或描述"
            clearable
            @input="handleSearch"
            @clear="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="selectedArtist"
            placeholder="选择艺人"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="artist in artists"
              :key="artist.id"
              :label="artist.name"
              :value="artist.id"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="representativeFilter"
            placeholder="代表作筛选"
            clearable
            @change="handleSearch"
          >
            <el-option label="代表作" :value="true" />
            <el-option label="非代表作" :value="false" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button @click="handleSearch" type="primary">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 批量操作工具栏 -->
    <div class="toolbar" v-if="selectedWorks.length > 0">
      <el-button type="danger" @click="handleBatchDelete">
        <el-icon><Delete /></el-icon>
        批量删除 ({{ selectedWorks.length }})
      </el-button>
    </div>

    <!-- 作品列表 -->
    <el-table
      v-loading="loading"
      :data="works"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column label="作品信息" min-width="300">
        <template #default="{ row }">
          <div class="work-info">
            <div class="work-title">{{ row.title }}</div>
            <div class="work-description" v-if="row.description">
              {{ row.description }}
            </div>
            <div class="work-meta">
              <el-tag v-if="row.isRepresentative" type="success" size="small">代表作</el-tag>
              <span class="duration" v-if="row.duration">{{ row.duration }}</span>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="艺人" width="150">
        <template #default="{ row }">
          <div class="artist-info" v-if="row.artist">
            <el-avatar :size="32" :src="row.artist.avatar" />
            <span class="artist-name">{{ row.artist.name }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="发布日期" width="120">
        <template #default="{ row }">
          <span v-if="row.releaseDate">
            {{ formatDate(row.releaseDate) }}
          </span>
          <span v-else class="text-muted">未设置</span>
        </template>
      </el-table-column>

      <el-table-column label="音频" width="120">
        <template #default="{ row }">
          <div class="audio-section">
            <audio 
              v-if="row.audioUrl" 
              :src="row.audioUrl" 
              controls 
              preload="none"
              style="width: 100px; height: 30px;"
            >
              您的浏览器不支持音频播放
            </audio>
            <span v-else class="text-muted">无音频</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="info" @click="handleManageAudio(row)">音频</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 创建/编辑对话框 -->
    <WorkDialog
      v-model="showCreateDialog"
      :work="editingWork"
      :artists="artists"
      @success="handleDialogSuccess"
    />


    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="showDeleteDialog"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除作品 "{{ deletingWork?.title }}" 吗？此操作不可恢复。</p>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete" :loading="deleting">确定删除</el-button>
      </template>
    </el-dialog>

    <!-- 音频管理对话框 -->
    <WorkAudioManager
      v-model="showAudioDialog"
      :work="selectedWork"
      @success="handleAudioSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Delete } from '@element-plus/icons-vue'
import WorkDialog from './components/WorkDialog.vue'
import WorkAudioManager from './components/WorkAudioManager.vue'
import { getWorkList, deleteWork, batchDeleteWorks } from '@/api/work'
// 修正：将 getArtistList 的导入路径改为正确的 api 目录
import { artistApi } from '@/api/index'
import type { Work, Artist } from '@/types'

// 响应式数据
const loading = ref(false)
const works = ref<Work[]>([])
const artists = ref<Artist[]>([])

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 搜索和筛选
const searchQuery = ref('')
const selectedArtist = ref<number | null>(null)
const representativeFilter = ref<boolean | null>(null)

// 对话框状态
const showCreateDialog = ref(false)
const showDeleteDialog = ref(false)
const showAudioDialog = ref(false)
const editingWork = ref<Work | null>(null)
const deletingWork = ref<Work | null>(null)
const selectedWork = ref<Work | null>(null)
const deleting = ref(false)

// 批量选择
const selectedWorks = ref<Work[]>([])

// 获取作品列表
const fetchWorks = async () => {
  try {
    loading.value = true
    const params: any = {
      page: pagination.page,
      limit: pagination.limit
    }
    
    if (searchQuery.value) {
      params.search = searchQuery.value
    }
    
    if (selectedArtist.value) {
      params.artistId = selectedArtist.value
    }
    
    if (representativeFilter.value !== null) {
      params.isRepresentative = representativeFilter.value
    }

    const response = await getWorkList(params)
    works.value = response.data.data
    pagination.total = response.data.pagination.total
    pagination.page = response.data.pagination.page
    pagination.limit = response.data.pagination.limit
  } catch (error) {
    console.error('获取作品列表失败:', error)
    ElMessage.error('获取作品列表失败')
  } finally {
    loading.value = false
  }
}

// 获取艺人列表
const fetchArtists = async () => {
  try {
    const response = await artistApi.getList({ limit: 1000 })
    
    // 检查响应结构
    if (response && response.data && response.data.data) {
      artists.value = response.data.data
    } else {
      artists.value = []
    }
  } catch (error) {
    console.error('获取艺人列表失败:', error)
    ElMessage.error('获取艺人列表失败')
    artists.value = []
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  fetchWorks()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchWorks()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchWorks()
}

// 选择处理
const handleSelectionChange = (selection: Work[]) => {
  selectedWorks.value = selection
}

// 编辑作品
const handleEdit = (work: Work) => {
  editingWork.value = work
  showCreateDialog.value = true
}

// 删除作品
const handleDelete = (work: Work) => {
  deletingWork.value = work
  showDeleteDialog.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!deletingWork.value) return
  
  try {
    deleting.value = true
    await deleteWork(deletingWork.value.id)
    ElMessage.success('删除成功')
    showDeleteDialog.value = false
    fetchWorks()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  } finally {
    deleting.value = false
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedWorks.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedWorks.value.length} 个作品吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedWorks.value.map(work => work.id)
    await batchDeleteWorks(ids)
    ElMessage.success('批量删除成功')
    selectedWorks.value = []
    fetchWorks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 对话框成功回调
const handleDialogSuccess = () => {
  showCreateDialog.value = false
  editingWork.value = null
  fetchWorks()
}

// 音频管理
const handleManageAudio = (work: Work) => {
  selectedWork.value = work
  showAudioDialog.value = true
}

// 音频操作成功回调
const handleAudioSuccess = () => {
  showAudioDialog.value = false
  selectedWork.value = null
  fetchWorks()
}

// 工具函数
const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (date: string) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 生命周期
onMounted(async () => {
  await fetchArtists() // 先获取艺人列表
  await fetchWorks()   // 再获取作品列表
})
</script>

<style lang="scss" scoped>
.work-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
  }
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 16px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.work-info {
  .work-title {
    font-weight: 600;
    margin-bottom: 4px;
  }
  
  .work-description {
    color: #666;
    font-size: 14px;
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .work-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .duration {
      color: #999;
      font-size: 12px;
    }
  }
}

.artist-info {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .artist-name {
    font-size: 14px;
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.text-muted {
  color: #999;
}
</style>
